package server

import (
	"LessUrl/dao"
	"flag"
	"fmt"
	"net/http"
	"net/rpc"
)

const AddForm = `
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
`

var (
	listenAddr = flag.String("http", ":8080", "http listen address")
	dataFile   = flag.String("file", "store.json", "data store file name")
	hostname   = flag.String("host", "110.40.155.17:8080", "host name and port")
	rpcEnabled = flag.Bool("rpc", false, "enable RPC server")
	masterAddr = flag.String("master", "", "RPC master address")
)

//注意接口已经是指针了,这一点和结构体不同
var store dao.Store

func Start() {
	flag.Parse()

	if *masterAddr != "" { // we are a slave
		store = dao.NewProxyStore(*masterAddr)
	} else { // we are the master
		store = dao.NewFileStore(*dataFile)
	}

	openRpc()

	http.HandleFunc("/", redirect)
	http.HandleFunc("/add", add)
	http.ListenAndServe(*listenAddr, nil)
}

func openRpc() {
	if *rpcEnabled {
		fmt.Println("开启RPC远程调用")
		rpc.RegisterName("FileStore", store)
		rpc.HandleHTTP()
	}
}

func add(w http.ResponseWriter, r *http.Request) {
	url := r.FormValue("url")

	if url == "" {
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprint(w, AddForm)
		return
	}

	var key string

	if err := store.Put(&url, &key); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "http://%s/%s", *hostname, key)
}

func redirect(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[1:]

	var url string

	if err := store.Get(&key, &url); err != nil || url == "" {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, url, http.StatusFound)
}
